//
//  simplest_eagl_ciimage.m
//  QH_Simplest_EAGL_Demo
//
//  Created by Anakin chen on 2021/2/17.
//

#import "simplest_eagl_ciimage.h"

@interface simplest_eagl_ciimage ()

@property (nonatomic, strong) GLKView *glkV;
@property (nonatomic, strong) CIContext *ciContext;

@property (nonatomic) CGRect glkBound;

@end

@implementation simplest_eagl_ciimage

+ (instancetype)createWith:(UIView *)preview {
    simplest_eagl_ciimage *this = [simplest_eagl_ciimage new];
    this.preview = preview;
    [this p_setup];
    return this;
}

+ (instancetype)createWith:(UIView *)preview ctx:(EAGLContext *)ctx {
    simplest_eagl_ciimage *this = [simplest_eagl_ciimage new];
    this.preview = preview;
    this.eaglContext = ctx;
    [this p_setup];
    return this;
}

#pragma mark - Pirvate

- (void)p_setup {
    [super p_setup];
    
    _glkV = [[GLKView alloc] initWithFrame:CGRectZero context:self.eaglContext];
    _glkV.contentScaleFactor = [UIScreen mainScreen].scale;
    _glkV.frame = CGRectMake(0, 0, self.preview.frame.size.width, self.preview.frame.size.height);
    [self.preview addSubview:_glkV];
    
    _ciContext = [CIContext contextWithEAGLContext:self.eaglContext];
    _glkBound = CGRectZero;//CGRectMake(0, 0, 410, 249);
    
    [self p_getGLKBound:CGSizeMake(410, 249)];
}

- (void)p_processVideoSampleBuffer2:(UIImage *)image {
    CIImage *ciImage;
    ciImage = [CIImage imageWithCGImage:image.CGImage];
    [_ciContext drawImage:ciImage inRect:_glkBound fromRect:ciImage.extent];
    [self.eaglContext presentRenderbuffer:GL_RENDERBUFFER];
}

#pragma mark - Util

- (void)p_getGLKBound:(CGSize)imageSize {
    if (CGRectEqualToRect(_glkBound, CGRectZero)) {
        CGFloat s = [UIScreen mainScreen].scale;
        CGFloat w = self.preview.frame.size.width * s;
        CGFloat h = self.preview.frame.size.width * s * (imageSize.height / imageSize.width);
        CGFloat y = (self.preview.frame.size.height * s - h) / 2;
        _glkBound = CGRectMake(0, y, w, h);
    }
}

@end
